package com.kefan.reptilemanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kefan.reptilemanagement.common.entities.*;
import com.kefan.reptilemanagement.common.errorHandler.BizException;
import com.kefan.reptilemanagement.mapper.SysUserMapper;
import com.kefan.reptilemanagement.service.*;
import com.kefan.reptilemanagement.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sjj
 * @since 2021-10-17
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysMenuService sysMenuService;

    @Autowired
    ApplicationService applicationService;

    @Autowired
    SpiderService spiderService;

    @Autowired
    TaskService taskService;

    @Autowired
    RedisUtil redisUtil;

    @Autowired SysUserService sysUserService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
     private SysUserRoleService sysUserRoleService;

    @Override
    public SysUser getByUsername(String username) {
        return getOne(new QueryWrapper<SysUser>().eq("username", username));
    }
/*
 * @Author sjj
 * @Description //TODO 根据用户ID获取权限字符串
 * @Date 2021/10/17 2021/10/17
 * @Param userId :用户id
 * @return 返回权限字符串
 **/

    @Override
    public String getUserAuthorityInfo(Long userId) {

        SysUser sysUser = sysUserMapper.selectById(userId);

        //  ROLE_admin,ROLE_normal,sys:user:list,....
        String authority = "";

        if (redisUtil.hasKey("GrantedAuthority:" + sysUser.getUsername())) {
            authority = (String) redisUtil.get("GrantedAuthority:" + sysUser.getUsername());

        } else {
            // 获取角色编码
            List<SysRole> roles = sysRoleService.list(new QueryWrapper<SysRole>()
                    .inSql("id", "select role_id from sys_user_role where user_id = " + userId));

            if (roles.size() > 0) {
                String roleCodes = roles.stream().map(r -> "ROLE_" + r.getCode()).collect(Collectors.joining(","));
                authority = roleCodes.concat(",");
            }

            // 获取菜单操作编码
            List<Long> menuIds = sysUserMapper.getNavMenuIds(userId);
            if (menuIds.size() > 0) {

                List<SysMenu> menus = sysMenuService.listByIds(menuIds);
                String menuPerms = menus.stream().map(m -> m.getPerms()).collect(Collectors.joining(","));

                authority = authority.concat(menuPerms);
            }

            redisUtil.set("GrantedAuthority:" + sysUser.getUsername(), authority, 60 * 60);
        }
        return authority;
    }
    /*
     * @Author sjj
     * @Description //TODO 以下方法都为删除用户权限缓存的方法
     * @Date 2021/10/17 2021/10/17
     **/

    @Override
    public void clearUserAuthorityInfo(String username) {
        redisUtil.del("GrantedAuthority:" + username);
    }

    @Override
    public void clearUserAuthorityInfoByRoleId(Long roleId) {

        List<SysUser> sysUsers = this.list(new QueryWrapper<SysUser>()
                .inSql("id", "select user_id from sys_user_role where role_id = " + roleId));

        sysUsers.forEach(u -> {
            this.clearUserAuthorityInfo(u.getUsername());
        });

    }

    @Override
    public void clearUserAuthorityInfoByMenuId(Long menuId) {
        List<SysUser> sysUsers = sysUserMapper.listByMenuId(menuId);

        sysUsers.forEach(u -> {
            this.clearUserAuthorityInfo(u.getUsername());
        });
    }

    @Override
    public Boolean delete(Integer id) {
        return sysUserMapper.deleteById(id) == 1;
    }


    @Override
    public List<SysUser> getUserList() {
        List<SysUser> list=sysUserMapper.selectList(null);
        for (int i=0;i<list.size();i++)
        {
            QueryWrapper<SysUserRole> wrapper=new QueryWrapper<>();

            wrapper.eq("user_id",list.get(i).getId());

            List<SysUserRole> sysUserRoleList=sysUserRoleService.list(wrapper);
            List<SysRole> sysRoles=new ArrayList<>();
            for(int j=0;j<sysUserRoleList.size();j++)
            {
                SysRole sysRole=new SysRole();
                sysRole.setId(sysUserRoleList.get(j).getRoleId());
                sysRoles.add(sysRole);
            }
            list.get(i).setSysRoles(sysRoles);
        }
        return list;
    }

    @Override
    public SysUser getUserInfoById(Integer id) {
        return sysUserMapper.selectById(id);
    }

    @Override
    public SysUser getCurrentUserInfo() {
        //获取当前用户名
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //获取当前用户
        SysUser sysUser = sysUserService.getByUsername(username);

        QueryWrapper<SysUserRole> wrapper=new QueryWrapper<>();

        wrapper.eq("user_id",sysUser.getId());

        List<SysUserRole> sysUserRoleList=sysUserRoleService.list(wrapper);
        List<SysRole> sysRoles=new ArrayList<>();
        for(int i=0;i<sysUserRoleList.size();i++)
        {
            SysRole sysRole=new SysRole();
            sysRole.setId(sysUserRoleList.get(i).getRoleId());
            sysRoles.add(sysRole);
        }
        sysUser.setSysRoles(sysRoles);

        return sysUser;
    }

    @Override
    public SysUser exchange(SysUser sysUser) {
        SysUser old =getById(sysUser.getId());
        if(old==null)
        {
            throw  new BizException("用户不存在!");
        }
        sysUser.setUpdated(LocalDateTime.now());
        updateById(sysUser);
        return sysUser;
    }

    @Override
    public ApplicationData getData() {
        //获取当前用户名
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //获取当前用户
        SysUser sysUser = sysUserService.getByUsername(username);
        QueryWrapper<SysUserRole> rwrapper=new QueryWrapper<>();

        rwrapper.eq("user_id",sysUser.getId());

        boolean flag=false;
        List<SysUserRole> sysUserRoleList=sysUserRoleService.list(rwrapper);
        for (int i=0;i<sysUserRoleList.size();i++)
        {
            if(sysUserRoleList.get(i).getRoleId()==6)
            {
                flag=true;
            }
        }
        List<SysRole> sysRoles=new ArrayList<>();
        QueryWrapper<Application>wrapper=new QueryWrapper<>();
        if (flag)
        {
            wrapper.eq("status",1);

        }
        else {
            wrapper.eq("status",1).and(qr->qr.eq("user_id",sysUser.getId()).or().eq("tech_id",sysUser.getId()));
        }
        List<Application> data=applicationService.list(wrapper);
        ApplicationData res=new ApplicationData();
        res.setPendingCount(data.size());
        QueryWrapper<Application>wrapper1=new QueryWrapper<>();
        if (flag)
        {
            wrapper1.eq("status",2);
        }
        else
        {
            wrapper1.eq("status",2).and(qr->qr.eq("user_id",sysUser.getId()).or().eq("tech_id",sysUser.getId()));

        }
        data=applicationService.list(wrapper1);
        res.setProcessingCount(data.size());
        QueryWrapper<Application>wrapper2=new QueryWrapper<>();
        if (flag)
        {
            wrapper2.eq("status",3);

        }
        else
        {
            wrapper2.eq("status",3).and(qr->qr.eq("user_id",sysUser.getId()).or().eq("tech_id",sysUser.getId()));

        }
        data=applicationService.list(wrapper2);
        res.setCompeletedCount(data.size());
        QueryWrapper<Application>wrapper3=new QueryWrapper<>();
        if(flag)
        {
            wrapper3.eq("status",4);
        }
        else
        {
            wrapper3.eq("status",4).and(qr->qr.eq("user_id",sysUser.getId()).or().eq("tech_id",sysUser.getId()));

        }
        data=applicationService.list(wrapper3);
        res.setCancelCount(data.size());
        data=applicationService.list();
        res.setTotal(data.size());
        return res;
    }

    @Override
    public Integer getUserCount() {
        List<SysUser> data=list();
        return data.size();
    }

    @Override
    public SpiderData getSpiderData() {
        //获取当前用户名
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //获取当前用户
        SysUser sysUser = sysUserService.getByUsername(username);
        QueryWrapper<SysUserRole> rwrapper=new QueryWrapper<>();

        rwrapper.eq("user_id",sysUser.getId());

        boolean flag=false;
        List<SysUserRole> sysUserRoleList=sysUserRoleService.list(rwrapper);
        for (int i=0;i<sysUserRoleList.size();i++)
        {
            if(sysUserRoleList.get(i).getRoleId()==6)
            {
                flag=true;
            }
        }

        QueryWrapper<Spider>wrapper=new QueryWrapper<>();
        if (flag)
        {
            wrapper.eq("status",3);

        }
        else
        {
            wrapper.eq("status",3).eq("tech_id",sysUser.getId());

        }
        List<Spider>spiderList=spiderService.list(wrapper);
        SpiderData data=new SpiderData();
        data.setCompeletedCount(spiderList.size());
        QueryWrapper<Spider>wrapper1=new QueryWrapper<>();
        if (flag)
        {
            wrapper1.eq("status",4);

        }
        else
        {
            wrapper1.eq("status",4).eq("tech_id",sysUser.getId());

        }
        spiderList=spiderService.list(wrapper1);
        data.setErrorCount(spiderList.size());
        spiderList=spiderService.list();
        data.setTotal(spiderList.size());
        return data;
    }

    @Override
    public TaskData getTaskData() {
        //获取当前用户名
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //获取当前用户
        SysUser sysUser = sysUserService.getByUsername(username);
        QueryWrapper<SysUserRole> rwrapper=new QueryWrapper<>();

        rwrapper.eq("user_id",sysUser.getId());

        boolean flag=false;
        List<SysUserRole> sysUserRoleList=sysUserRoleService.list(rwrapper);
        for (int i=0;i<sysUserRoleList.size();i++)
        {
            if(sysUserRoleList.get(i).getRoleId()==6)
            {
                flag=true;
            }
        }
        QueryWrapper<Task>wrapper=new QueryWrapper<>();
        if (flag)
        {
            wrapper.eq("status",1);
        }
        else
        {
            wrapper.eq("status",1).eq("user_id",sysUser.getId());

        }
        List<Task>taskList=taskService.list(wrapper);
        TaskData data=new TaskData();
        data.setPendingCount(taskList.size());
        QueryWrapper<Task>wrapper1=new QueryWrapper<>();
        if(flag)
        {
            wrapper1.eq("status",2);
        }
        else
        {
            wrapper1.eq("status",2).eq("user_id",sysUser.getId());

        }
        taskList=taskService.list(wrapper1);
        data.setProcessingCount(taskList.size());
        taskList=taskService.list();
        data.setTotal(taskList.size());
        QueryWrapper<Task>wrapper2=new QueryWrapper<>();
        if (flag)
        {
            wrapper2.eq("status",3);
        }
        else
        {
            wrapper2.eq("status",3).eq("user_id",sysUser.getId());

        }
        taskList=taskService.list(wrapper2);
        data.setCompeletedCount(taskList.size());
        QueryWrapper<Task>wrapper3=new QueryWrapper<>();
        if (flag)
        {
            wrapper3.eq("status",4);
        }
        else
        {
            wrapper3.eq("status",4).eq("user_id",sysUser.getId());

        }
        taskList=taskService.list(wrapper3);
        data.setErrorCount(taskList.size());
        return data;
    }

    @Override
    public List<TimeApplication> getTimeData() {
        //获取当前用户名
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //获取当前用户
        SysUser sysUser = sysUserService.getByUsername(username);
        QueryWrapper<SysUserRole> rwrapper=new QueryWrapper<>();

        rwrapper.eq("user_id",sysUser.getId());

        boolean flag=false;
        List<SysUserRole> sysUserRoleList=sysUserRoleService.list(rwrapper);
        for (int i=0;i<sysUserRoleList.size();i++)
        {
            if(sysUserRoleList.get(i).getRoleId()==6)
            {
                flag=true;
            }
        }
        LocalDateTime starttime=LocalDateTime.of(LocalDateTime.now().getYear(),LocalDateTime.now().getMonth(),LocalDateTime.now().getDayOfMonth(),0,0);
        LocalDateTime endtime=LocalDateTime.of(LocalDateTime.now().getYear(),LocalDateTime.now().getMonth(),LocalDateTime.now().getDayOfMonth(),23,59);
        QueryWrapper<Task> wrapper=new QueryWrapper<>();
        if (flag)
        {
            wrapper.between("created",starttime,endtime);
        }
        else
        {
            wrapper.between("created",starttime,endtime).eq("user_id",sysUser.getId());

        }
        TimeApplication timeApplication=new TimeApplication();
        List<Task> tasks=new ArrayList<>();
        tasks=taskService.list(wrapper);
        timeApplication.setTime(starttime);
        timeApplication.setCount(tasks.size());
        List<TimeApplication> res=new ArrayList<>();
        res.add(timeApplication);
        LocalDateTime starttime1=starttime.minusDays(1);
        LocalDateTime endtime1=endtime.minusDays(1);
        wrapper=new QueryWrapper<>();
        if (flag)
        {
            wrapper.between("created",starttime1,endtime1);
        }
        else
        {
            wrapper.between("created",starttime1,endtime1).eq("user_id",sysUser.getId());

        }
        tasks=taskService.list(wrapper);
        TimeApplication timeApplication1=new TimeApplication();
        timeApplication1.setCount(tasks.size());
        timeApplication1.setTime(starttime1);
        res.add(timeApplication1);

        starttime1=starttime.minusDays(2);
        endtime1=endtime.minusDays(2);
        wrapper=new QueryWrapper<>();
        if (flag)
        {
            wrapper.between("created",starttime1,endtime1);
        }
        else
        {
            wrapper.between("created",starttime1,endtime1).eq("user_id",sysUser.getId());

        }
        tasks=taskService.list(wrapper);
        TimeApplication timeApplication2=new TimeApplication();
        timeApplication2.setCount(tasks.size());
        timeApplication2.setTime(starttime1);
        res.add(timeApplication2);

        starttime1=starttime.minusDays(3);
        endtime1=endtime.minusDays(3);
        wrapper=new QueryWrapper<>();
        if (flag)
        {
            wrapper.between("created",starttime1,endtime1);
        }
        else
        {
            wrapper.between("created",starttime1,endtime1).eq("user_id",sysUser.getId());

        }
        tasks=taskService.list(wrapper);
        TimeApplication timeApplication3=new TimeApplication();
        timeApplication3.setCount(tasks.size());
        timeApplication3.setTime(starttime1);
        res.add(timeApplication3);

        starttime1=starttime.minusDays(4);
        endtime1=endtime.minusDays(4);
        wrapper=new QueryWrapper<>();
        if (flag)
        {
            wrapper.between("created",starttime1,endtime1);
        }
        else
        {
            wrapper.between("created",starttime1,endtime1).eq("user_id",sysUser.getId());

        }
        tasks=taskService.list(wrapper);
        TimeApplication timeApplication4=new TimeApplication();
        timeApplication4.setCount(tasks.size());
        timeApplication4.setTime(starttime1);
        res.add(timeApplication4);
        return res;

    }

    @Override
    public SysUser register(SysUser sysUser)
    {
        sysUser.setCreated(LocalDateTime.now());
        //设置密码
        String password=passwordEncoder.encode(sysUser.getPassword());
        sysUser.setPassword(password);
        //设置头像
        sysUser.setAvatar(Constraint.DEFULT_AVATAR);
        sysUser.setStatu(Constraint.STATUS_ON);
        //正则表达校验

        //插入数据
        sysUserService.save(sysUser);
        //给用户初始化为普通用户
        SysUserRole sysUserRole=new SysUserRole();
        sysUserRole.setUserId(sysUser.getId())
                .setRoleId(sysUser.getRoleId());
        sysUserRoleService.save(sysUserRole);
        return sysUser;

    }


}
